package com.chenqi.myblog.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chenqi.myblog.model.Blog;
import com.chenqi.myblog.model.PageInfo;
import com.chenqi.myblog.model.Type;
import com.chenqi.myblog.model.User;
import com.chenqi.myblog.service.BlogService;
import com.chenqi.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @description:
 * @program: myblog
 * @author: ChenQi
 * @create: 2021-02-2021/2/2-09-51
 */
@Controller
@RequestMapping("/admin")
public class ABlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Value("${adminBlog.page}")
    private Integer adminPage;

    @Value("${adminBlog.rows}")
    private Integer adminRows;

    /**
     * 后台查看博客列表
     * @param modelAndView
     * @return
     */
    @GetMapping("/blog_list")
    public ModelAndView listBlog(ModelAndView modelAndView) {
        //如果没有传分页信息则进行预处理
        List<Blog> allBlog = blogService.findAllBlog();
        modelAndView.addObject("blogs", allBlog);
        modelAndView.setViewName("admin/blogs");
        return modelAndView;
    }

    /**
     * 添加博客
     * @param blog
     * @param modelAndView
     * @param session
     * @return
     */
    @PostMapping("/saveBlog")
    public ModelAndView saveBlog(@RequestParam(value = "tags",required = false) Integer[] tags, Blog blog, ModelAndView modelAndView, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Type type = typeService.findTypeById(blog.getTypeId());
        blog.setTypeName(type.getName());
        blog.setUserAvatar(user.getAvatar());
        blog.setUserId(user.getId());
        blog.setUserUsername(user.getUsername());
        blogService.saveBlog(blog);
        //保存对应博客与标签的关系
        for (int i = 0; i <tags.length; i++) {
            blogService.saveTags(blog.getId(),tags[i]);
        }
        modelAndView.setViewName("redirect:/admin/blog_list");
        return modelAndView;
    }

    /**
     * 删除博客
     * @param id
     * @param modelAndView
     * @return
     */
    @GetMapping("/deleteBlog")
    public ModelAndView deleteBlog(@RequestParam(value = "id") Integer id,ModelAndView modelAndView) {
        blogService.deleteBlog(id);
        modelAndView.setViewName("redirect:/admin/blog_list");
        return modelAndView;
    }
}
